import baseURL from "./config.js"
import {
		useStore
	} from '@/store/index.js'
// 全局请求封装
export default (path, data = {}, method) => {
	const urlArr = ['/user/login', '/user/verify']
	// #ifdef H5
	const token = useStore().token || 'f2650c644ea03c0f4cfb8025fe9436a5'
	// #endif
	//#ifdef MP-WEIXIN
	const token = useStore().token
	let needLogin = urlArr.includes(path)
	if (!token && !needLogin) {
		uni.reLaunch({
			url: '/pages/login/index'
		})
		return false
	}
	// #endif

	return new Promise((resolve, reject) => {
		wx.request({
			header: {
				token
			},
			url: baseURL.baseURL + path,
			method,
			data,
			success(response) {
				console.log(response)
				
				
				if (response.data.code === 401) {
					uni.showToast({
						title: '登陆已失效，请从新登录！',
						icon: "none",
						duration: 4000,
					})
					uni.removeStorageSync('token')
					
					uni.reLaunch({
						url: '/pages/login/index'
					})
					return false
				}

				if (response.data.code === 200 || response.data=="success") {
					
						resolve(response.data)
					

				} else {
					uni.showToast({
						title: response.data.msg,
						icon: "none",
						duration: 4000,
					})
					reject()
				}


			},
			fail(err) {
				uni.showToast({
					title: err,
					icon: 'none'
				});

				reject(err)
			},
			complete(res) {
				console.log(res)
				if (!res.statusCode) {
					uni.hideLoading()
					uni.showToast({
						title: '请检查网络是否连接',
						icon: "none",
						duration: 4000,
					})
					reject()
					return false
				}
				if (res.statusCode === 400) {
					uni.hideLoading()
					uni.showToast({
						title: res.statusCode + ' 无法找到请求的资源',
						icon: "none",
						duration: 4000,
					})
					reject()
					return false
				}
				if (res.statusCode === 403) {
					uni.hideLoading()
					uni.showToast({
						title: res.statusCode + ' 没有权限访问资源',
						icon: "none",
						duration: 4000,
					})
					reject()
					return false
				}
				if (res.statusCode === 404) {
					uni.hideLoading()
					uni.showToast({
						title: res.statusCode + ' 访问的目标资源不存在',
						icon: "none",
						duration: 4000,
					})
					reject()
					return false
				}

				if (res.statusCode === 500) {
					uni.hideLoading()
					uni.showToast({
						title: res.statusCode + ' 服务器内部代码错误',
						icon: "none",
						duration: 4000,
					})
					reject()
					return false
				}
			}
		});
	});
}